<template>
    <div class="generator-table-page">
        <el-card class="search-box">
            <el-form :inline="true" :model="searcForm" class="search-form">
                <el-form-item label="表名称">
                    <el-input v-model="searcForm.tableName" placeholder="表名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="表描述">
                    <el-input v-model="searcForm.tableDescribe" placeholder="表描述" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch" plain>查询</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="table-list">
            <div style="display: flex;margin-bottom: 15px;">
                <el-button type="primary" plain @click="handleExport">导入</el-button>
                <el-button type="primary" plain @click="handlePreview">预览</el-button>
                <el-button type="primary" plain @click="handleDownload">生成</el-button>
                <el-button type="success" plain @click="handleEdit">修改</el-button>
                <el-button type="danger" plain @click="handleDelete">删除</el-button>
            </div>
            <div class="table-container">
                <el-table :data="tableData" :stripe="true" :border="true" :highlight-current-row="true"
                    style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column type="index" width="60" label="序号" align="center" />
                    <el-table-column prop="tableName" label="表名称" align="center"></el-table-column>
                    <el-table-column prop="tableDescribe" label="表描述" align="center"></el-table-column>
                    <el-table-column prop="className" label="实体类名称" align="center"></el-table-column>
                    <el-table-column prop="tableAuthor" label="表作者" align="center"></el-table-column>
                    <el-table-column prop="packageName" label="包名称" align="center"></el-table-column>
                    <el-table-column prop="packagePath" label="包路径" align="center"></el-table-column>
                    <el-table-column prop="remark" label="备注" align="center"></el-table-column>
                    <el-table-column prop="operate" label="操作" align="center" width="260">
                        <template #default="scope">
                            <el-button type="primary" plain size="small"
                                @click="() => handleEdit(scope.row.id)">修改</el-button>
                            <el-button type="info" plain size="small"
                                @click="() => handlePreview(scope.row.id)">预览</el-button>
                            <el-button type="info" plain size="small"
                                @click="() => handleDownload(scope.row.id)">生成</el-button>
                            <el-button type="danger" plain size="small"
                                @click="() => handleDelete(scope.$index + 1, scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="table-pagination">
                <el-pagination v-model:current-page="searcForm.pageNum" v-model:page-size="searcForm.pageSize"
                    :page-sizes="[10, 20, 30, 50]" background layout="total, sizes, prev, pager, next, jumper"
                    :page-count="pageCount" :total="total" @size-change="onSearch" @current-change="onSearch" />
            </div>
        </el-card>
        <TableForm ref="GeneratorTableFromRef" v-model:dialogFrom="dialogFrom" @onParentSearch="onSearch">
        </TableForm>
        <ExportDatabaseTable ref="ExportDatabaseTableRef"
            v-model:GeneratorExportDatabaseTableDialogVisible="GeneratorExportDatabaseTableDialogVisible"
            @onParentSearch="onSearch">
        </ExportDatabaseTable>
        <PreviewGenerate v-model:dialogFrom="previewGenerateDialog"></PreviewGenerate>
    </div>
</template>
<script lang="ts" setup>
// ---------------------------------------------------导入相关引用---------------------------------------------------
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import TableForm, { type DialogFrom } from '@/views/generator/components/TableForm.vue';
import ExportDatabaseTable from '@/views/generator/components/ExportDatabaseTable.vue';
import PreviewGenerate, { type DialogFrom as PreviewDialogFrom } from '@/views/generator/components/PreviewGenerate.vue';
import { getList, delteInfo, type SearchListParams, downloadCode } from '@/api/generator/generator';

// ---------------------------------------------------相关参数定义---------------------------------------------------
const searcForm = ref<SearchListParams>({
    pageNum: 1,
    pageSize: 10,
    tableName: '',
    tableDescribe: '',
});

const tableData = ref<TableItem[]>([]);
const pageCount = ref(0);
const total = ref(0);
const selectionTableDataList = ref<number[]>([]);

const dialogFrom = ref<DialogFrom>({
    dialogTitle: '新增',
    dialogVisble: false,
    infoId: null
});

const previewGenerateDialog = ref<PreviewDialogFrom>({
    dialogTitle: '预览',
    dialogVisble: false,
    infoId: []
});

const GeneratorExportDatabaseTableDialogVisible = ref(false);
// ---------------------------------------------------操作方法定义---------------------------------------------------
/**
 * 页面加载时回调
 * @returns void
 */
onMounted(() => {
    onSearch();
});

const handleSelectionChange = (val: TableItem[]) => {
    selectionTableDataList.value = val.map((item) => {
        return item.id;
    });
};

/**
 * 导入
 */
const handleExport = () => {
    GeneratorExportDatabaseTableDialogVisible.value = true;
};

/**
 * 预览
 * @param rowId id
 */
const handlePreview = (rowId: number | number[]) => {
    if (typeof rowId !== 'number') {
        if (selectionTableDataList.value.length == 0) {
            ElMessage.warning('请选择一条数据');
            return;
        } 
        rowId = selectionTableDataList.value;
    }
    previewGenerateDialog.value.dialogVisble = true;
    previewGenerateDialog.value.infoId = rowId;
};

const handleDownload = (rowId: number | number[]) => {
    if (typeof rowId !== 'number') {
        if (selectionTableDataList.value.length == 0) {
            ElMessage.warning('请选择一条数据');
            return;
        } 
        rowId = selectionTableDataList.value;
    }
    ElMessageBox.confirm('确定要生成选中的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        downloadCode(rowId);
    }).catch(() => { })
};

/**
 * 修改
 * @param index 索引
 * @param id id
 */
const handleEdit = (rowId: number) => {
    if (typeof rowId !== 'number') {
        if (selectionTableDataList.value.length == 0) {
            ElMessage.warning('请选择一条数据');
            return;
        } else if (selectionTableDataList.value.length > 1) {
            ElMessage.warning('只能选择一条数据');
            return;
        }
        rowId = selectionTableDataList.value[0];
    }

    const table = tableData.value.find((item: TableItem) =>  item.id == rowId);
    if(!table){
        ElMessage.warning('数据不存在,请刷新列表重试！');
        return;
    }
    dialogFrom.value.dialogTitle = '修改' + table.tableName;
    dialogFrom.value.dialogVisble = true;
    dialogFrom.value.infoId = rowId;
};

/**
 * 删除
 * @param index 索引
 * @param id id
 */
const handleDelete = (index: number, id: number) => {
    if (typeof id === 'number') {
        hendleDeleteApi(index, id)
    } else {
        if (selectionTableDataList.value.length == 0) {
            ElMessage.warning('请选择一条数据');
        } else {
            hendleDeleteApi(index, selectionTableDataList.value)
        }
    }
};

const hendleDeleteApi = (index: number, rowId: number | number[]) => {
    ElMessageBox.confirm('确定要删除选中的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        delteInfo(rowId).then((res) => {
            if (res.data.code === 200) {
                ElMessage.success('删除成功');
                onSearch();
            }
        })
    }).catch(() => { })
}

/**
 * 查询
 */
const onSearch = () => {
    getList(searcForm.value).then((res) => {
        if (res.data.code === 200) {
            tableData.value = res.data.data.records;
            pageCount.value = res.data.data.pages;
            total.value = res.data.data.total;
        }
    });
};

// ---------------------------------------------------实体定义区---------------------------------------------------
/**
 * 表格数据项
 */
interface TableItem {
    id: number;
    tableName: string;
    tableDescribe: string;
    className: string;
    tableAuthor: string;
    packageName: string;
    packagePath: string;
    remark: string;
}
</script>

<style lang="scss" scoped>
.generator-table-page {
    width: 100%;
    height: 100%;
}
</style>